package so.shanku.essential.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import aym.util.sdcard.SdcardHelper;
import aym.util.versionup.IVersionSelectedCallBack;
import aym.util.versionup.VersionUpdateUtil;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.fragment.*;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Confing;
import so.shanku.essential.view.WihteRoundCornersDialog;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Jaelyn on 2015/8/17 0017.
 */
public class MainActivity extends BaseActivity {
    private int currentSelectItem = -1;
    //底部导航栏
    @ViewInject(id = R.id.tab_bottom_layout)
    private RadioGroup tab_bottom_layout;

    /**
     * 选项卡展示页
     */
    @ViewInject(id = R.id.fragment_layout)
    private LinearLayout fragment_layout;

    /**
     * 保存点击过得fragment
     */
    private HashMap<Integer, BaseFragment> fragments = new HashMap();

    // 版本升级的工具
    private VersionUpdateUtil util;
    // 内存卡管理的帮助类
    private SdcardHelper sdHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        tab_bottom_layout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setSelectItem(checkedId);
            }
        });
        setSelectItem(0);
        upversion();
    }

    /**
     * 检测版本
     */
    private void upversion() {
        util = VersionUpdateUtil.init(this);
        sdHelper = new SdcardHelper();

        if (!sdHelper.ExistSDCard()) {
            //toast.showToast(R.string.nosdcard);
        } else {
            util.doSelectVersion(GetDataConfing.ip,
                    GetDataConfing.Action_selectAppVersionInfo, null, false,
                    versionSelectedCallBack);
        }
    }

    String apkDownLoadPath;

    /**
     * 提示用户有新版本
     */
    private void showNewVersion(JsonMap<String, Object> info,
                                String versionName, int versionCode) {
        apkDownLoadPath = info.getStringNoNull("VersionPath");
        builder = new WihteRoundCornersDialog(mContext,
                R.style.ExitDialogStyle, 2, callBackdialog1);
        builder.setTitletext(R.string.app_version_select);
        builder.setMessagetext(info.getStringNoNull("Description"));
        builder.setButtonText(R.string.app_version_iknow, R.string.app_version_update);
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog1 = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:
                    break;
                case 2:
                    String appName = getString(R.string.app_name);
                    util.doUpdateVersion(apkDownLoadPath,
                            Confing.productPath + appName + ".apk",
                            appName, R.drawable.app_icon, true);

                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };

    IVersionSelectedCallBack versionSelectedCallBack = new IVersionSelectedCallBack() {
        @Override
        public void netError(String arg0) {
            // toast.showToast(R.string.neterror);
        }

        @Override
        public boolean isUpdate(String serviceInfo, String versionName,
                                int versionCode) {
            try {
                serviceInfo = serviceInfo.substring(serviceInfo.indexOf("{"),
                        serviceInfo.lastIndexOf("}") + 1);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            if (ShowGetDataError.isCodeIsNot1(mContext, serviceInfo)) {
                List<JsonMap<String, Object>> infoData = JsonParseHelper
                        .getJsonMap_List_JsonMap(serviceInfo, JsonKeys.Key_Info);
                if (infoData.size() == 0) {

                } else {
                    JsonMap<String, Object> info = infoData.get(0);
                    if (info.getStringNoNull("VersionNo").equals(versionName)
                            || "".equals(info.getStringNoNull("VersionNo"))
                            || "".equals(info.getStringNoNull("VersionPath"))) {
                        //toast.showToast(R.string.app_version_newest);
                    } else {
                        showNewVersion(info, versionName, versionCode);
                    }
                }

            } else {

            }
            return false;
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
//		if(currentSelectItem==0){
//			((ShopMallFragment)currentFragment).refreshShoppingCartNum();
//			((ShopMallFragment)currentFragment).refreshPushMsgNum();
//		}
    }

    //设置选中项和展示
    public void setSelectItem(int checkedId) {
        int selectItem = 0;
        if (checkedId == R.id.shopping_page_tv) {
            selectItem = 1;
        } else if (checkedId == R.id.find_page_tv) {
            selectItem = 0;
        } else if (checkedId == R.id.home_page_tv) {
            selectItem = 2;
        } else if (checkedId == R.id.community_page_tv) {
            selectItem = 3;
        } else if (checkedId == R.id.userCenter_page_tv) {
            selectItem = 4;
        }

        if (currentSelectItem != selectItem) {
            if (currentSelectItem == 6) {
                currentSelectItem = 3;
            }
            currentSelectItem = selectItem;
            switch (selectItem) {
                case 0:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        FindProductFragment findProductFragment = new FindProductFragment();
                        fragments.put(selectItem, findProductFragment);
                        replaceView(findProductFragment);
                    }
                    //replaceView(new HomePageFragment());

                    break;
                case 1:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        ShopMallFragment shopMallFragment = new ShopMallFragment();
                        fragments.put(selectItem, shopMallFragment);
                        replaceView(shopMallFragment);
                    }
                    break;
                case 2:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        ShoppingMallFragment shoppingMallFragment = new ShoppingMallFragment();
                        fragments.put(selectItem, shoppingMallFragment);
                        replaceView(shoppingMallFragment);
                    }
                    break;
                case 3:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        CommunityFragment shoppingBrandFragment = new CommunityFragment();
                        fragments.put(selectItem, shoppingBrandFragment);
                        replaceView(shoppingBrandFragment);
                    }
                    break;
                case 4:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        UserCenterFragment userCenterFragment = new UserCenterFragment();
                        fragments.put(selectItem, userCenterFragment);
                        replaceView(userCenterFragment);
                    }
                    break;
                default:
                    break;
            }

        }
    }


    private BaseFragment currentFragment;

    private void replaceView(BaseFragment fragment) {
        if (currentFragment != fragment) {
            FragmentTransaction transaction = this.getSupportFragmentManager()
                    .beginTransaction();
//			FragmentTransaction transaction = mFragmentMan.beginTransaction().setCustomAnimations(
//					android.R.anim.fade_in, R.anim.slide_out);
            if (currentFragment != null) {
                if (!fragment.isAdded()) {    // 先判断是否被add过
                    transaction.hide(currentFragment).add(R.id.fragment_layout, fragment).commit(); // 隐藏当前的fragment，add下一个到Activity中
                } else {
                    transaction.hide(currentFragment).show(fragment).commit(); // 隐藏当前的fragment，显示下一个
                }
            } else {
                transaction.add(R.id.fragment_layout, fragment).commit(); // add下一个到Activity中
            }
            currentFragment = fragment;
        }
    }

    @Override
    public void onBackPressed() {
          if(currentFragment.backKeyClick()){
               super.onBackPressed();
          } else {
              showExitDialog();
          }

    }

    WihteRoundCornersDialog builder;

    private void showExitDialog() {

        builder = new WihteRoundCornersDialog(this,
                R.style.ExitDialogStyle, 2, callBackdialog);
        builder.setTitletext("温馨提示");
        builder.setMessagetext("是否确认退出？");
        builder.setButtonText("取消", "确定");
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    MainActivity.this.finish();
                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };

}